/*
  User: MissingAeon
  Date: 2024/5/17
  Time: 11:53
--*/
import { defineStore } from "pinia";
import { nextTick, ref } from "vue";
import { PrivateLetterService } from "@/api";
import { PrivateMessageVo } from "@/api";

export interface PrivateMessageItem {
  data: PrivateMessageVo;
  selected: boolean;
}

export const usePrivateMessageStore = defineStore("privateMessage", () => {
  const privateMessageList = ref<PrivateMessageItem[]>([]);
  const selectedItem = ref<PrivateMessageVo>({
    newMessagesCount: 0,
    privateId: 0,
    targetUser: {
      userId: 0,
      nickname: "",
      avatar: "",
      newsNumbers: 0,
      status: "OFFLINE",
    },
  });

  const refreshCallback: (() => void)[] = [];

  /**
   * 获取私信列表
   */
  async function refresh() {
    const result = await PrivateLetterService.privateMessageList();
    if (result && result.data) {
      // 更新私信列表
      privateMessageList.value = (result.data as PrivateMessageVo[]).map(
        (item) => {
          console.log(item);
          return {
            data: item,
            selected: false,
          };
        }
      ) as PrivateMessageItem[];
      await nextTick();
      refreshCallback.forEach((item) => {
        item && item();
      });
      // 清空
      refreshCallback.length = 0;
    }
  }

  /**
   * 选择私信
   * @param item 目标项
   * @param refreshed 是否已刷新完成，false如果未刷新完成，则等待刷新完成后再进行选择
   */
  function selectItem(item: PrivateMessageItem | number, refreshed = false) {
    if (typeof item === "number") {
      // 查询出对应的私信
      const privateLetterItem = privateMessageList.value.filter(
        (i: PrivateMessageItem) => {
          return i.data.privateId === item;
        }
      )[0];
      if (privateLetterItem) {
        selectItem(privateLetterItem);
      } else {
        if (!refreshed) {
          // 等待刷新
          refreshCallback.push(() => {
            selectItem(item, true);
          });
        } else {
          // 刷新失败
          console.error("错误的私信ID");
        }
      }
    } else {
      // 选中私信
      privateMessageList.value.forEach((i: PrivateMessageItem) => {
        i.selected = false;
      });
      // 选中当前私信
      item.selected = true;
      selectedItem.value = item.data;
    }
  }

  return { privateMessageList, selectedItem, refresh, selectItem };
});
